/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tcpclient;

import ObserverPattern.Observable;
import ObserverPattern.ObserverInterface;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Home
 */
public class TCPClient implements Runnable,Observable {
    
    //Needed to implement the Observer pattern.
    private String state; 
    //Added a string to hold the content of the file
    private  static String fileContent="";
    //Counter flag to get make the difference between the two files 
    static int counter =0;
    
    private  String address;
    private Thread runner;          // Thread object that this class runs in
    static long startTime;                 // record start time of run()
    static long endTime;                   // record end time of run()
    private static String addressF1 = "https://dl.dropbox.com/u/2076201/longfile.txt";   // address of default f1
    private static String addressF2 = "https://dl.dropbox.com/u/2076201/shortfile.txt";   // address of default f2
    
    
    //The constructor to call to start the threads
    public TCPClient(String faddress,GUI mygui) 
    {
       //Add the GUI class as an observer for this thread
        addObserver(mygui);
        
        this.address = faddress;    // set TCPClient address
       
        if (null == runner) {
            runner = new Thread(this);
            runner.start();         // call run()
        }
        
       
    }
    
    //The constructor for the Main fuction to run it in command mode
    public TCPClient(String faddress) 
    {
       
        this.address = faddress;    // set TCPClient address
       
        if (null == runner) {
            runner = new Thread(this);
            runner.start();         // call run()
        }
        
       
    }
    
    
    
    //Constructor to call from the GUI for Option1
    public TCPClient(GUI mygui)
    {
       TCPClient tcpClientF1 = new TCPClient(addressF1,mygui);
       TCPClient tcpClientF2 = new TCPClient(addressF2,mygui); 
       
    }
    //Constructor to call from the GUI for Option2
    public TCPClient(GUI mygui,String address1,String address2)
    {
       TCPClient tcpClientF3 = new TCPClient(address1,mygui);
       TCPClient tcpClientF4 = new TCPClient(address2,mygui); 
       
    }
   
    public void run() {

        startTime = System.nanoTime();  // start a timer to record run time
        try {
            getData(address);
            // getData() from address
        } catch (MalformedURLException ex) {
            Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private synchronized void   getData(String address) throws MalformedURLException, IOException {
            URL file = new URL(address);   
        BufferedReader in = new BufferedReader(
        new InputStreamReader(file.openStream()));

        String inputLine;
        //construct the string filecontent with the content of the streamed file
        while ((inputLine = in.readLine()) != null)
        {
        fileContent+= inputLine + "\n"; 
        }
        in.close();
        endTime = System.nanoTime();    // cancel timer to record run time
        
        //Notify the GUI class that reading file is done
        //and pass the name of the file as a message
        if (counter == 0)
        {
        setState("File1");
        counter++;
         //Reset the value of the shared variable filecontent so we can re
         //reconstruct it with a different thread.
        fileContent="";
        }
        else if (counter == 1)
        {
         setState("File2");  
         counter = 0;
         //Reset the value of the shared variable filecontent so we can re
         //reconstruct it with a different thread.
         fileContent="";
        }
        
         
        }
    
    //Return the value of the elapsed time to GUI 
    public long GetElapsedTime( )
    {
        return this.endTime - this.startTime;
    }
    //Return the value of the file time to GUI 
    public synchronized String GetFile()
    {
        return fileContent;
    }



    

    /**
     * @param args the command line arguments
     */
    
    public static void main(String[] args) {
        
        TCPClient tcpClientF1 = new TCPClient(addressF1);
        TCPClient tcpClientF2 = new TCPClient(addressF2);
        
    }
    
   
    
    
    
    
    /*****************************************/
    //implementation of the Observable pattern//
    /********************************************/
   private List observers = new ArrayList();
   
     
       @Override
     public String getState() 
     {
         return state;
     }
         
    @Override
     public synchronized void setState(String state) 
     {
         this.state = state;
         notifyObservers();
     }
     
    @Override
     public void addObserver(ObserverInterface o) 
     {
         observers.add(o);
     }
    @Override
     public void removeObserver(ObserverInterface o)
     {
         observers.remove(o);
     }
     public synchronized void notifyObservers()
     {
         Iterator i = observers.iterator();
         while (i.hasNext()) 
         {
             ObserverInterface o = (ObserverInterface) i.next();
             o.Update(this);
         }
     }
    
    
    
    
    
    
    
}
